package com.mnnu.utils;

import com.mnnu.config.JwtProperties;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class JwtUtils {

    @Autowired
    private JwtProperties jwtProperties;

    // 生成jwt令牌
    public String generateJwt(Map<String, Object> claims) {
        String secret = jwtProperties.getSecret();
        Long expiration = jwtProperties.getExpiration();

        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .compact();
        return jwt;
    }

    // 解析jwt令牌
    public List<String> parseJwt(String jwt) {
        String secret = jwtProperties.getSecret();

        Claims body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(jwt)
                .getBody();

        Integer idInt = (Integer) body.get("id");
        String id = String.valueOf(idInt);
        String username = (String) body.get("username");
        String password = (String) body.get("password");
        List<String> info = List.of(id, username, password);

        return info;
    }
}
